<?php

namespace App\Http\Controllers\Entity\Column;

use App\Classes\Publish\Publication;
use App\Http\Controllers\Controller;
use App\Http\Requests\Entity\Column\SubcolumnRequest;
use App\Jobs\Publish\SubcolumnJob;
use App\Models\Common\CatData\Video\Vcat;
use App\Models\Common\CatData\Video\Vccat;
use App\Models\Common\CatData\Video\Vccattag;
use App\Models\Common\EntityData\Channel\Ogroup;
use App\Models\Common\EntityData\Channel\Sp;
use App\Models\Common\TagData\Video\Vcattag;
use App\Models\Entity\Asset\Video\Vasseti;
use App\Models\Entity\Asset\Vlive\Vchan;
use App\Models\Entity\Column\Column;
use App\Models\Entity\Column\Subcolumn;
use App\Models\Entity\Column\SubcolumnVasseti;
use App\Models\Entity\Column\SubcolumnVchan;
use App\Repositories\Entity\Column\SubcolumnRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;
use Validator;

class SubcolumnController extends Controller
{
    use ModelForm;

    /** @var  SubcolumnRepository */
    private $subcolumnRepository;

    public function __construct(SubcolumnRepository $subcolumnRepo)
    {
        $this->subcolumnRepository = $subcolumnRepo;
    }

    /**
     * Display a listing of the Subcolumn.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        return Admin::content(function (Content $content) use ($request) {

            $content->header(__('entity.column.subcolumns.index_header'));
            $content->description(__('entity.column.subcolumns.index_description'));

            $content->body($this->grid($request));
        });
    }

    /**
     * Show the form for creating a new Subcolumn.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.column.subcolumns.create_header'));
            $content->description(__('entity.column.subcolumns.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Subcolumn in storage.
     *
     * @param SubcolumnRequest $request
     *
     * @return Response
     */
    public function store(SubcolumnRequest $request)
    {
        $input = $request->all();
        $image = $request->file('img'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.subcolumn');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // $rootDir      = config('filesystems.disks.' . $driver . '.root');

                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                // $rootDir  = config('filesystems.disks.'.$driver.'.root');
                // $fullPath = $dir . '/' . $newImageName;
                // 修改input
                // $input['img'] = $rootDir . $fullPath;

                $input['img'] = $fullPath;

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }
        $subcolumn = $this->subcolumnRepository->create($input);

        if ($subcolumn) {
            // 2017/08/23 tian modify 添加媒资为跳转编辑
            // 手动添加-中间表
            // if (is_array($request->get('vassetis'))) {
            //     $subcolumn->vassetis()->sync(array_filter($request->get('vassetis')));
            // }
        }

        Flash::success(__('entity.column.subcolumns.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.column.subcolumns.index'));

    }

    /**
     * Display the specified Subcolumn.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $subcolumn = $this->subcolumnRepository->findWithoutFail($id);

        if (empty($subcolumn)) {
            Flash::error(__('entity.column.subcolumns.not_found'));

            return redirect(route('entity.column.subcolumns.index'));
        }

        return view('entity.column.subcolumns.show')->with('subcolumn', $subcolumn);

    }

    /**
     * Show the form for editing the specified Subcolumn.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('entity.column.subcolumns.edit_header'));
            $content->description(__('entity.column.subcolumns.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Subcolumn in storage.
     *
     * @param  int              $id
     * @param SubcolumnRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $subcolumn = $this->subcolumnRepository->findWithoutFail($id);

        if (empty($subcolumn)) {
            Flash::error(__('entity.column.subcolumns.not_found'));

            return redirect(route('entity.column.subcolumns.index'));
        }

        $input = $request->all();

        if (array_key_exists('_file_del_', $input)) {

            $imgUrl       = $subcolumn->img;
            $uploadConfig = config('custom.base.upload.subcolumn');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];

            if ($flag = Storage::disk($driver)->delete($imgUrl)) {
                $subcolumn->img = null;
                $subcolumn->save();
                return response()->json(['message' => '图片删除成功!', 'status' => $flag]);
            }

            return response()->json(['message' => '图片删除失败!', 'status' => $flag]);
        }

        $sValidators = [
            'name'       => 'required|max:100',
            'title'      => 'max:100',
            'subtitle'   => 'max:100',
            'column_id'  => 'required|max:100',
            // 'img'        => 'max:200',
            'online_at'  => 'date',
            'offline_at' => 'date',
            'status'     => 'required',
            'short_desc' => 'max:100',
            'listorder'  => 'required|numeric',
        ];

        $validators = [];

        // 判断是否行内编辑,只有下线的可以编辑
        $status = Subcolumn::where(['online_status' => 0, 'id' => $id])->first();
        if ($status) {
            $input = $this->handleEditable($input);
        }

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }

        // 定义校验, 没有移到request
        $validator = Validator::make($input, $validators, [
            // 'required' => ':attribute 不能为空',
        ], [
            'name'       => '名称',
            'title'      => '标题',
            'subtitle'   => '副标题',
            'column_id'  => '栏目',
            'online_at'  => '上线时间',
            'offline_at' => '下线时间',
            'status'     => '状态',
            'short_desc' => '描述',
            'listorder'  => '排序',
        ]
        );

        // 校验
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        // 排序
        if ($this->handleOrderable($id, $input)) {
            return response([
                'status'  => true,
                'message' => trans('admin::lang.update_succeeded'),
            ]);
        }

        $image = $request->file('img'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.subcolumn');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // $rootDir      = config('filesystems.disks.' . $driver . '.root');

                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                // $rootDir  = config('filesystems.disks.'.$driver.'.root');
                // $fullPath = $dir . '/' . $newImageName;
                // 修改input
                // $input['img'] = $rootDir . $fullPath;

                $input['img'] = $fullPath;

                // 2017/08/22 modify
                // 删除原先存储的图片
                $flag = Storage::disk($driver)->delete($subcolumn->img);

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));

            }
        }
        $subcolumn = $this->subcolumnRepository->update($input, $id);

        if ($subcolumn) {
            // 2017/08/23 tian modify 添加媒资为跳转编辑
            // 手动添加-中间表
            // if (is_array($request->get('vassetis'))) {
            //     $subcolumn->vassetis()->sync(array_filter($request->get('vassetis')));
            // }
        }

        Flash::success(__('entity.column.subcolumns.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.column.subcolumns.index'));
    }

    /**
     * Remove the specified Subcolumn from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        } else {
            // 只有下线且下线发布的才能删除
            $subcolumn = Subcolumn::where('id', $id)->where(['online_status' => 0, 'publish_down_status' => 1])->first();
            if (empty($subcolumn)) {
                return response()->json(['message' => '只有状态为下线且已下线发布的才可以删除', 'status' => false]);
            }
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            // 只有下线且下线发布的才能删除
            $id = Subcolumn::whereIn('id', $id)->where(['online_status' => 0, 'publish_down_status' => 1])->pluck('id')->toArray();
            if ($flag = $this->subcolumnRepository->batchDelete('id', $id)) {
                return response()->json(['message' => __('entity.column.subcolumns.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => '只有状态为下线发布的才可以删除', 'status' => $flag]);
            }
        }

        $subcolumn = $this->subcolumnRepository->findWithoutFail($id);

        if (empty($subcolumn)) {
            Flash::error(__('entity.column.subcolumns.not_found'));

            return redirect(route('entity.column.subcolumns.index'));
        }

        // 2017/08/22 modify
        // $imgUrl       = $subcolumn->img;
        // $uploadConfig = config('custom.base.upload.subcolumn');
        // $driver       = $uploadConfig['driver'];
        // $dir          = $uploadConfig['dir'];

        // 根据配置得到根路径
        // $rootDir = config('filesystems.disks.' . $driver . '.upload');

        // $rootDir  = config('filesystems.disks.'.$driver.'.root');
        // $imgUrl = strchr($imgUrl, $rootDir);

        if ($flag = $this->subcolumnRepository->delete($id)) {

            // 2017/08/22 modify
            // $bool = Storage::disk($driver)->delete($imgUrl);

            $subcolumn->vassetis()->detach();

            return response()->json(['message' => __('entity.column.subcolumns.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [editAsset 编辑媒资界面]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    // public function editAsset($id)
    // {
    //     $subcolumn = $this->subcolumnRepository->findWithoutFail($id);

    //     if (empty($subcolumn)) {
    //         Flash::error(__('entity.column.subcolumns.not_found'));

    //         return redirect(route('entity.column.subcolumns.index'));
    //     }

    //     // // 只能手动调用下函数
    //     // Admin::script('entityColumnSubcolumnAsset();');
    //     // // 分类
    //     // $vcats = Vcat::get(['name', 'id']);
    //     // // 归类数据
    //     // $vcattags = Vcattag::get(['name', 'id']);
    //     $tab = new Tab();
    //     $tab->add('添加点播媒资', $this->editVasset($id));
    //     $tab->add('添加直播媒资', $this->editVchan($id));
    //     return $tab;
    //     // return view('entity.column.subcolumn.asset', ['vcats' => $vcats, 'vcattags' => $vcattags, 'subcolumn_id' => $id]);
    // }

    public function editAsset($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('添加媒资'));

            // if (Request::get('view') !== 'table') {
            //     $grid->view('admin.grid.card');
            // }
            // 剧集详情
            // $content->row($this->assetDetailsBox($id));

            // 分集数据
            $content->row($this->vassetiTab($id));
            // $content->body($this->vassetiGrid($id));
        });
    }

    // 剧集tab
    public function vassetiTab($id)
    {
        $tab = new Tab();

        $tab->add('编辑点播媒资', $this->editVasseti($id));
        $tab->add('编辑直播媒资', $this->editVchan($id));
        return $tab;
    }

    /**
     * [编辑点播媒资]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function editVasseti($id)
    {
        // 只能手动调用下函数
        Admin::script('entityColumnSubcolumnAsset();');
        // 分类
        $vcats = Vcat::get(['name', 'id']);
        // 归类数据
        $vcattags = Vcattag::get(['name', 'id']);
        return view('entity.column.subcolumn.asset', ['vcats' => $vcats, 'vcattags' => $vcattags, 'subcolumn_id' => $id]);
    }

    /**
     * [selected 已选的媒资数据]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function selectedVasseti(Request $request)
    {
        if ($request->ajax()) {
            /**
             * 过滤字段
             */
            // 归类
            $vcat = $request->input('vcat');
            // 分类
            $vcattag = $request->input('vcattag');
            // 搜索框的值
            $search_value = $request->input('search_value');
            // 二级栏目id
            $subcolumn_id = $request->input('subcolumn_id');
            // 收费类型
            $charge_type = $request->input('charge_type');

            $data                 = array();
            $data['draw']         = $request->get('draw');
            $start                = $request->get('start') ?: 0;
            $length               = $request->get('length') ?: 10;
            $order                = $request->get('order');
            $columns              = $request->get('columns');
            $search               = $request->get('search');
            $data['recordsTotal'] = SubcolumnVasseti::whereHas('subcolumn', function ($query) use ($subcolumn_id) {
                if (!empty($subcolumn_id)) {
                    $query = $query->where('id', '=', $subcolumn_id);
                }
            })->count();

            if ($order) {
                $orderColumData = $columns[$order[0]['column']]['data'];
            }

            // 排序字段
            $ord = '';
            if (!empty($orderColumData)) {
                $ord = $orderColumData . ' ' . $order[0]['dir'];
            } else {
                $ord = 'id asc';
            }
            $data['recordsFiltered'] = SubcolumnVasseti::with(['subcolumn', 'vasseti', 'vasseti.vcat', 'vasseti.actors', 'vasseti.directors', 'vasseti.vareas', 'vasseti.vlangs', 'vasseti.vyears', 'vasseti.vcattags'])
                ->whereHas('vasseti.vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vasseti.vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->whereHas('subcolumn', function ($query) use ($subcolumn_id) {
                    if (!empty($subcolumn_id)) {
                        $query = $query->where('id', '=', $subcolumn_id);
                    }
                })
                ->whereHas('vasseti', function ($query) use ($search_value, $charge_type) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if ($charge_type == '0' || $charge_type == '1') {
                        $query = $query->where('charge_type', '=', $charge_type);
                    }
                })->count();

            $data['data'] = SubcolumnVasseti::with(['subcolumn', 'vasseti.vcat', 'vasseti.actors', 'vasseti.directors', 'vasseti.vareas', 'vasseti.vlangs', 'vasseti.vyears', 'vasseti.vcattags'])
                ->whereHas('vasseti.vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vasseti.vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->whereHas('subcolumn', function ($query) use ($subcolumn_id) {
                    if (!empty($subcolumn_id)) {
                        $query = $query->where('id', '=', $subcolumn_id);
                    }
                })
                ->whereHas('vasseti', function ($query) use ($search_value, $charge_type) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if ($charge_type == '0' || $charge_type == '1') {
                        $query = $query->where('charge_type', '=', $charge_type);
                    }
                })
                ->skip($start)->take($length)
                ->orderByRaw($ord)
                ->get();
            return response()->json($data);
        }
        return response()->json(['status' => 'error', 'content' => '非法操作']);
    }


    public function allContent(Request $request){
        //return response()->json(['status' => 'error', 'content' => '非法操作']);
        if (!$request->ajax()) {
            return response()->json(['status' => 'error', 'content' => '非法操作']);
        }if($request->input('content_model') == 'App\Models\Entity\Asset\Video\Vasseti'){
            return $this->vassetiData($request);
        }elseif ($request->input('content_model') == 'App\Models\Entity\Asset\Vlive\Vchan'){
            //return response()->json(['status' => 'error', 'content' => '非法操作2']);
            return $this->vchanData($request);
        }
    }

    /**
     * [data 媒资数据]
     * @return [type] [description]
     */
    public function vassetiData(Request $request)
    {
        if ($request->ajax()) {
            /**
             * 过滤字段
             */
            // 归类
            $vcat = $request->input('vcat');
            // 分类
            $vcattag = $request->input('vcattag');
            // 搜索框的值
            $search_value = $request->input('search_value');
            // 二级栏目id
            $subcolumn_id = $request->input('subcolumn_id');
            // 收费类型
            $charge_type          = $request->input('charge_type');
            $data                 = array();
            $data['draw']         = $request->get('draw');
            $start                = $request->get('start') ?: 0;
            $length               = $request->get('length') ?: 10;
            $order                = $request->get('order');
            $columns              = $request->get('columns');
            $search               = $request->get('search');
            $data['recordsTotal'] = Vasseti::where(function ($query) use ($subcolumn_id) {
                if (!empty($subcolumn_id)) {
                    $query = $query->whereNotIn('id', SubcolumnVasseti::where(['subcolumn_id' => $subcolumn_id])->pluck('vasseti_id')->toArray());
                }
            })->count();

            if ($order) {
                $orderColumData = $columns[$order[0]['column']]['data'];
            }

            // 排序字段
            $ord = '';
            if (!empty($orderColumData)) {
                $ord = $orderColumData . ' ' . $order[0]['dir'];
            } else {
                $ord = 'id asc';
            }

            $data['recordsFiltered'] = Vasseti::with(['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'])
                // ->whereHas('vcat', function ($query) use ($vcat) {
                //     if (!empty($vcat)) {
                //         $query = $query->where('id', $vcat);
                //     }
                // })
                // ->whereHas('vcattags', function ($query) use ($vcattag) {
                //     if (!empty($vcattag)) {
                //         $query = $query->where('vcattag_id', $vcattag);
                //     }
                // })
                ->where(function ($query) use ($charge_type) {
                    if ($charge_type == '0' || $charge_type == '1') {
                        $query = $query->where('charge_type', '=', $charge_type);
                    }
                })
                ->where(function ($query) use ($search_value, $subcolumn_id) {
                    if (!empty($search_value)) {
                        $query = $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if (!empty($subcolumn_id)) {
                        $query = $query->whereNotIn('id', SubcolumnVasseti::where(['subcolumn_id' => $subcolumn_id])->pluck('vasseti_id')->toArray());
                    }
                })
                ->count();

            $data['data'] = Vasseti::with(['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags','tags'])
                // ->whereHas('vcat', function ($query) use ($vcat) {
                //     if (!empty($vcat)) {
                //         $query = $query->where('id', $vcat);
                //     }
                // })
                // ->whereHas('vcattags', function ($query) use ($vcattag) {
                //     if (!empty($vcattag)) {
                //         $query = $query->where('vcattag_id', $vcattag);
                //     }
                // })
                ->where(function ($query) use ($charge_type) {
                    if ($charge_type == '0' || $charge_type == '1') {
                        $query = $query->where('charge_type', '=', $charge_type);
                    }
                })
                ->where(function ($query) use ($search_value, $subcolumn_id) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if (!empty($subcolumn_id)) {
                        $query = $query->whereNotIn('id', SubcolumnVasseti::where(['subcolumn_id' => $subcolumn_id])->pluck('vasseti_id')->toArray());
                    }
                })
                ->skip($start)->take($length)
                ->orderByRaw($ord)
                ->get();
            return response()->json($data);
        }

        return response()->json(['status' => 'error', 'content' => '非法操作']);
    }

    /**
     * 添加单个媒资|多个媒资
     * @param Request $request [description]
     */
    public function addVasseti(Request $request)
    {
        $subcolumn_id = $request->input('subcolumn_id');
        $vasseti_id   = $request->input('vasseti_id');

        // 如果二级栏目已经上线且发布,则不让新增、删除操作
        $data = Subcolumn::where('id', '=', $subcolumn_id)->select(['online_status', 'publish_status'])->first();

        if ($data && $data->online_status == 1 && $data->publish_status == 1) {
            return response()->json(['content' => '该二级栏目已上线发布,不能添加媒资!', 'status' => false]);
        }

        if (empty($subcolumn_id)) {
            return response()->json(['content' => '二级栏目为空!', 'status' => false]);
        }
        if (empty($vasseti_id)) {
            return response()->json(['content' => '媒资为空!', 'status' => false]);
        }
        // 判断是否为批量添加
        if (is_array($vasseti_id)) {
            foreach ($vasseti_id as $value) {
                $flag = SubcolumnVasseti::where(['subcolumn_id' => $subcolumn_id, 'vasseti_id' => $value])->first();
                if ($flag) {
                    return response()->json(['content' => '不能重复添加已经存在的媒资!', 'status' => false]);
                } else {
                    $subcolumnVasseti               = new SubcolumnVasseti();
                    $subcolumnVasseti->subcolumn_id = $subcolumn_id;
                    $subcolumnVasseti->vasseti_id   = $value;
                    if (!$subcolumnVasseti->save()) {
                        return response()->json(['content' => '添加失败!', 'status' => false]);
                    }
                }
            }
            return response()->json(['content' => '添加成功！', 'status' => true]);
        }

        $flag = SubcolumnVasseti::where(['subcolumn_id' => $subcolumn_id, 'vasseti_id' => $vasseti_id])->first();
        if ($flag) {
            return response()->json(['content' => '该媒资已经存在,不能重复添加!', 'status' => false]);
        } else {
            $subcolumnVasseti               = new SubcolumnVasseti();
            $subcolumnVasseti->subcolumn_id = $subcolumn_id;
            $subcolumnVasseti->vasseti_id   = $vasseti_id;
            $flag                           = $subcolumnVasseti->save();
            if ($flag) {
                return response()->json(['content' => '添加成功!', 'status' => $flag]);
            } else {
                return response()->json(['content' => '添加失败!', 'status' => $flag]);
            }
        }
    }

    /**
     * 删除单个媒资|多个媒资
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function deleteVasseti(Request $request)
    {
        $subcolumn_id = $request->input('subcolumn_id');
        $vasseti_id   = $request->input('vasseti_id');

        // 如果二级栏目已经上线且发布,则不让新增、删除操作
        $data = Subcolumn::where('id', '=', $subcolumn_id)->select(['online_status', 'publish_status'])->first();

        if ($data && $data->online_status == 1 && $data->publish_status == 1) {
            return response()->json(['content' => '该二级栏目已上线发布,不能删除媒资!', 'status' => false]);
        }

        if (empty($subcolumn_id)) {
            return response()->json(['content' => '二级栏目为空!', 'status' => false]);
        }
        if (empty($vasseti_id)) {
            return response()->json(['content' => '媒资为空!', 'status' => false]);
        }
        // 判断是否为批量删除
        if (is_array($vasseti_id)) {
            foreach ($vasseti_id as $value) {
                $flag = SubcolumnVasseti::where(['subcolumn_id' => $subcolumn_id, 'vasseti_id' => $value])->delete();

                if (!$flag) {
                    return response()->json(['content' => '删除失败!', 'status' => $flag]);
                }
            }
            return response()->json(['content' => '删除成功!', 'status' => true]);
        }

        $flag = SubcolumnVasseti::where(['subcolumn_id' => $subcolumn_id, 'vasseti_id' => $vasseti_id])->delete();

        if ($flag) {
            return response()->json(['content' => '删除成功!', 'status' => $flag]);
        } else {
            return response()->json(['content' => '删除失败!', 'status' => $flag]);

        }
    }

    /**
     * [编辑直播媒资]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function editVchan($id)
    {
        // 只能手动调用下函数
        Admin::script('entityColumnSubcolumnVchan();');
        // 分类
        $vccats = Vccat::get(['name', 'id']);
        // 归类数据
        $vccattags = Vccattag::get(['name', 'id']);
        return view('entity.column.subcolumn.vchan', ['vccats' => $vccats, 'vccattags' => $vccattags, 'subcolumn_id' => $id]);
    }

    /**
     * [selected 已选的媒资数据]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function selectedVchan(Request $request)
    {
        if ($request->ajax()) {
            /**
             * 过滤字段
             */
            // 归类
            $vccat = $request->input('vccat');
            // 分类
            $vccattag = $request->input('vccattag');
            // 搜索框的值
            $search_value = $request->input('search_value');
            // 二级栏目id
            $subcolumn_id = $request->input('subcolumn_id');

            $data                 = array();
            $data['draw']         = $request->get('draw');
            $start                = $request->get('start') ?: 0;
            $length               = $request->get('length') ?: 10;
            $order                = $request->get('order');
            $columns              = $request->get('columns');
            $search               = $request->get('search');
            $data['recordsTotal'] = SubcolumnVchan::whereHas('subcolumn', function ($query) use ($subcolumn_id) {
                if (!empty($subcolumn_id)) {
                    $query = $query->where('id', '=', $subcolumn_id);
                }
            })->count();

            if ($order) {
                $orderColumData = $columns[$order[0]['column']]['data'];
            }

            // 排序字段
            $ord = '';
            if (!empty($orderColumData)) {
                $ord = $orderColumData . ' ' . $order[0]['dir'];
            } else {
                $ord = 'id asc';
            }
            $data['recordsFiltered'] = SubcolumnVchan::with(['subcolumn', 'vchan', 'vchan.vccat', 'vchan.vcareacats', 'vchan.vlangs', 'vchan.vccattags'])
                ->whereHas('vchan.vccat', function ($query) use ($vccat) {
                    if (!empty($vccat)) {
                        $query = $query->where('id', $vccat);
                    }
                })
                ->whereHas('vchan.vccattags', function ($query) use ($vccattag) {
                    if (!empty($vccattag)) {
                        $query = $query->where('vccattag_id', $vccattag);
                    }
                })
                ->whereHas('subcolumn', function ($query) use ($subcolumn_id) {
                    if (!empty($subcolumn_id)) {
                        $query = $query->where('id', '=', $subcolumn_id);
                    }
                })
                ->whereHas('vchan', function ($query) use ($search_value) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                })->count();

            $data['data'] = SubcolumnVchan::with(['subcolumn', 'vchan', 'vchan.vccat', 'vchan.vcareacats', 'vchan.vlangs', 'vchan.vccattags'])
                ->whereHas('vchan.vccat', function ($query) use ($vccat) {
                    if (!empty($vccat)) {
                        $query = $query->where('id', $vccat);
                    }
                })
                ->whereHas('vchan.vccattags', function ($query) use ($vccattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vccattag_id', $vccattag);
                    }
                })
                ->whereHas('subcolumn', function ($query) use ($subcolumn_id) {
                    if (!empty($subcolumn_id)) {
                        $query = $query->where('id', '=', $subcolumn_id);
                    }
                })
                ->whereHas('vchan', function ($query) use ($search_value) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                })
                ->skip($start)->take($length)
                ->orderByRaw($ord)
                ->get();
            return response()->json($data);
        }
        return response()->json(['status' => 'error', 'content' => '非法操作']);
    }

    /**
     * [data 媒资数据]
     * @return [type] [description]
     */
    public function vchanData(Request $request)
    {
        if ($request->ajax()) {
            /**
             * 过滤字段
             */
            // 归类
            $vccat = $request->input('vccat');
            // 分类
            $vccattag = $request->input('vccattag');
            // 搜索框的值
            $search_value = $request->input('search_value');
            // 二级栏目id
            $subcolumn_id = $request->input('subcolumn_id');

            $data         = array();
            $data['draw'] = $request->get('draw');
            $start        = $request->get('start') ?: 0;
            $length       = $request->get('length') ?: 10;
            $order        = $request->get('order');
            $columns      = $request->get('columns');
            $search       = $request->get('search');
            // $data['recordsTotal'] = Vasseti::onlineStatus()->onlinePublished()->
            //     where(function ($query) use ($subcolumn_id) {
            //     if (!empty($subcolumn_id)) {
            //         $query = $query->whereNotIn('id', SubcolumnVasseti::where(['subcolumn_id' => $subcolumn_id])->pluck('vasseti_id')->toArray());
            //     }
            // })
            //     ->count();
            $data['recordsTotal'] = Vchan::where(function ($query) use ($subcolumn_id) {
                if (!empty($subcolumn_id)) {
                    $query = $query->whereNotIn('id', SubcolumnVchan::where(['subcolumn_id' => $subcolumn_id])->pluck('vchan_id')->toArray());
                }
            })->count();
            if ($order) {
                $orderColumData = $columns[$order[0]['column']]['data'];
            }
            // 排序字段
            $ord = '';
            if (!empty($orderColumData)) {
                $ord = $orderColumData . ' ' . $order[0]['dir'];
            } else {
                $ord = 'id asc';
            }
            // $data['recordsFiltered'] = Vchan::onlineStatus()->onlinePublished()->with(['vccat','vcareacats', 'vlangs','vccattags'])
            $data['recordsFiltered'] = Vchan::with(['vccat', 'vcareacats', 'vlangs', 'vccattags'])
                ->whereHas('vccat', function ($query) use ($vccat) {
                    if (!empty($vccat)) {
                        $query = $query->where('id', $vccat);
                    }
                })
                ->whereHas('vccattags', function ($query) use ($vccattag) {
                    if (!empty($vccattag)) {
                        $query = $query->where('vccattag_id', $vccattag);
                    }
                })
                ->where(function ($query) use ($search_value, $subcolumn_id) {
                    if (!empty($search_value)) {
                        $query = $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if (!empty($subcolumn_id)) {
                        $query = $query->whereNotIn('id', SubcolumnVchan::where(['subcolumn_id' => $subcolumn_id])->pluck('vchan_id')->toArray());
                    }
                })->count();
            // $data['data'] = Vchan::onlineStatus()->onlinePublished()->with(['vccat','vcareacats', 'vlangs','vccattags'])
            $data['data'] = Vchan::with(['vccat', 'vcareacats', 'vlangs', 'vccattags'])
                ->whereHas('vccat', function ($query) use ($vccat) {
                    if (!empty($vccat)) {
                        $query = $query->where('id', $vccat);
                    }
                })
                ->whereHas('vccattags', function ($query) use ($vccattag) {
                    if (!empty($vccattag)) {
                        $query = $query->where('vccattag_id', $vccattag);
                    }
                })
                ->where(function ($query) use ($search_value, $subcolumn_id) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if (!empty($subcolumn_id)) {
                        $query = $query->whereNotIn('id', SubcolumnVchan::where(['subcolumn_id' => $subcolumn_id])->pluck('vchan_id')->toArray());
                    }
                })
                ->skip($start)->take($length)
                ->orderByRaw($ord)
                ->get();

            return response()->json($data);
        }
        return response()->json(['status' => 'error', 'content' => '非法操作']);
    }

    /**
     * 添加单个媒资|多个媒资
     * @param Request $request [description]
     */
    public function addVchan(Request $request)
    {
        $subcolumn_id = $request->input('subcolumn_id');
        $vchan_id     = $request->input('vchan_id');

        // 如果二级栏目已经上线且发布,则不让新增、删除操作
        $data = Subcolumn::where('id', '=', $subcolumn_id)->select(['online_status', 'publish_status'])->first();

        if ($data && $data->online_status == 1 && $data->publish_status == 1) {
            return response()->json(['content' => '该二级栏目已上线发布,不能添加媒资!', 'status' => false]);
        }

        if (empty($subcolumn_id)) {
            return response()->json(['content' => '二级栏目为空!', 'status' => false]);
        }
        if (empty($vchan_id)) {
            return response()->json(['content' => '媒资为空!', 'status' => false]);
        }
        // 判断是否为批量添加
        if (is_array($vchan_id)) {
            foreach ($vchan_id as $value) {
                $flag = SubcolumnVchan::where(['subcolumn_id' => $subcolumn_id, 'vchan_id' => $value])->first();
                if ($flag) {
                    return response()->json(['content' => '不能重复添加已经存在的媒资!', 'status' => false]);
                } else {
                    $subcolumnVchan               = new SubcolumnVchan();
                    $subcolumnVchan->subcolumn_id = $subcolumn_id;
                    $subcolumnVchan->vchan_id     = $value;
                    if (!$subcolumnVchan->save()) {
                        return response()->json(['content' => '添加失败!', 'status' => false]);
                    }
                }
            }
            return response()->json(['content' => '添加成功！', 'status' => true]);
        }

        $flag = SubcolumnVchan::where(['subcolumn_id' => $subcolumn_id, 'vchan_id' => $vchan_id])->first();
        if ($flag) {
            return response()->json(['content' => '该媒资已经存在,不能重复添加!', 'status' => false]);
        } else {
            $subcolumnVchan               = new SubcolumnVchan();
            $subcolumnVchan->subcolumn_id = $subcolumn_id;
            $subcolumnVchan->vchan_id     = $vchan_id;
            $flag                         = $subcolumnVchan->save();
            if ($flag) {
                return response()->json(['content' => '添加成功!', 'status' => $flag]);
            } else {
                return response()->json(['content' => '添加失败!', 'status' => $flag]);
            }
        }
    }

    /**
     * 删除单个媒资|多个媒资
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function deleteVchan(Request $request)
    {
        $subcolumn_id = $request->input('subcolumn_id');
        $vchan_id     = $request->input('vchan_id');

        // 如果二级栏目已经上线且发布,则不让新增、删除操作
        $data = Subcolumn::where('id', '=', $subcolumn_id)->select(['online_status', 'publish_status'])->first();

        if ($data && $data->online_status == 1 && $data->publish_status == 1) {
            return response()->json(['content' => '该二级栏目已上线发布,不能删除媒资!', 'status' => false]);
        }

        if (empty($subcolumn_id)) {
            return response()->json(['content' => '二级栏目为空!', 'status' => false]);
        }
        if (empty($vchan_id)) {
            return response()->json(['content' => '媒资为空!', 'status' => false]);
        }
        // 判断是否为批量删除
        if (is_array($vchan_id)) {
            foreach ($vchan_id as $value) {
                $flag = SubcolumnVchan::where(['subcolumn_id' => $subcolumn_id, 'vchan_id' => $value])->delete();

                if (!$flag) {
                    return response()->json(['content' => '删除失败!', 'status' => $flag]);
                }
            }
            return response()->json(['content' => '删除成功!', 'status' => true]);
        }

        $flag = SubcolumnVchan::where(['subcolumn_id' => $subcolumn_id, 'vchan_id' => $vchan_id])->delete();

        if ($flag) {
            return response()->json(['content' => '删除成功!', 'status' => $flag]);
        } else {
            return response()->json(['content' => '删除失败!', 'status' => $flag]);

        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Subcolumn::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('name', '名称')->help('必填');
            $form->text('title', '标题');
            $form->text('subtitle', '副标题');
            $sps = Sp::pluck('name', 'id');
            $form->select('sp_id', 'SP')->options($sps);
            $ogroups = Ogroup::pluck('name', 'id');
            $form->select('ogroup_id', '渠道')->options($ogroups);
            $form->textarea('onclick', 'onclick点击事件');
            $form->textarea('onfocus', 'onfocus焦点事件');
            $form->text('restful', 'restful路由');
            $form->textarea('description', '描述');
            $Columns = Column::pluck('name', 'id');
            $form->select('column_id', '栏目')->options($Columns);
            $form->image('img', '栏目图片')->removable();
            $form->date('online_at', '上线日期')->default(date('Y-m-d',time()))->help('必填');
            $form->date('offline_at', '下线日期')->default(date('Y-m-d',time()))->help('必填');
            $form->radio('status', '状态')->options([
                'online'  => '上线',
                'offline' => '下线',
                'stop'    => '停用',
            ])->default('offline');
            // 2017/08/23 tian modify 添加媒资为跳转编辑
            // $vassetis = Vasseti::pluck('name', 'id');
            // $form->multipleSelect('vassetis', '剧集')->options($vassetis);
            $form->text('short_desc', '简介');
            $form->textarea('long_desc', '详述');
            $form->number('listorder', '排序');

            $form->display('created_at', __('base.created_at'));
            $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid(Request $request)
    {

        return Admin::grid(Subcolumn::class, function (Grid $grid) use ($request) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // 状态过滤
            Publication::statusFilter($request->input('status'), $request->input('published'), $grid);
            // //添加按钮
            // if (!\Gate::check('entity.column.subcolumns.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     //编辑按钮
            //     if (!\Gate::check('entity.column.subcolumns.edit')) {
            //         $actions->disableEdit();
            //     }
            //     //删除按钮
            //     if (!\Gate::check('entity.column.subcolumns.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // //导出按钮
            // if (!\Gate::check('entity.column.subcolumns.export')) {
            //     $grid->disableExport();
            // }

            // //批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         //批量删除按钮
            //         if (!\Gate::check('entity.column.subcolumns.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 表格中的按钮
            $grid->actions(function ($actions) {
                $publish_down_status = $actions->row->publish_down_status;
                $publish_status      = $actions->row->publish_status;
                $online_status       = $actions->row->online_status;
                $id                  = $actions->getKey();
                // 媒资编辑
                // if ($publish_down_status === 1 && $online_status === 0 && Admin::user()->can('entity.column.subcolumns.edit_asset')) {
                if (Admin::user()->can('entity.column.subcolumns.edit_asset')) {
                    $url = route('entity.column.subcolumns.edit_asset', ['subcolumns' => $id]);
                    $actions->prepend('<a href ="' . $url . '" title="编辑媒资"><i class="fa fa-list"></i></a>');
                }
                // 上线发布按钮
                if ($publish_status === 0 && $online_status === 1 && Admin::user()->can('entity.column.subcolumns.publish_one')) {
                    $url      = route('entity.column.subcolumns.publish_one');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'publish',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线发布"><i class="fa fa-cloud-upload"></i></a>');
                }
                // 下线发布按钮
                if ($publish_down_status === 0 && $online_status === 0 && Admin::user()->can('entity.column.subcolumns.publish_down_one')) {
                    $url      = route('entity.column.subcolumns.publish_down_one');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'publishDown',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线发布"><i class="fa fa-cloud-download"></i></a>');
                }
                // 上线按钮
                if ($publish_down_status === 1 && $online_status === 0 && Admin::user()->can('entity.column.subcolumns.up')) {
                    $url      = route('entity.column.subcolumns.up');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'up',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线"><i class="fa fa-arrow-up"></i></a>');
                }
                // 下线按钮
                if ($online_status === 1 && Admin::user()->can('entity.column.subcolumns.down')) {
                    $url      = route('entity.column.subcolumns.down');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'down',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="下线"><i class="fa fa-arrow-down"></i></a>');
                }
                // 编辑按钮
                if (Admin::user()->cannot('entity.column.subcolumns.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('entity.column.subcolumns.destroy')) {
                    $actions->disableDelete();
                }
                // 只有状态下线的资源才可以编辑, 删除
                if ($publish_down_status === 0) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                }
            });

            // 添加按钮
            if (Admin::user()->cannot('entity.column.subcolumns.create')) {
                $grid->disableCreation();
            }

            // 导出按钮
            if (Admin::user()->cannot('entity.column.subcolumns.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $url2 = route('entity.column.subcolumns.progress');
                // 下线发布功能
                if (Admin::user()->can('entity.column.subcolumns.publish_down')) {
                    $url      = route('entity.column.subcolumns.publish_down');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-info pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-download"></i>下线发布</a>');
                }
                // 上线发布功能
                if (Admin::user()->can('entity.column.subcolumns.publish')) {
                    $url      = route('entity.column.subcolumns.publish');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-info pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-upload"></i>上线发布</a>');
                }
                // 全部下线功能
                if (Admin::user()->can('entity.column.subcolumns.all_down')) {
                    $url      = route('entity.column.subcolumns.all_down');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-danger pull-right" style="margin-right: 10px"> <i class="fa fa-arrow-down"></i>全部下线</a>');
                }
                // 全部上线功能
                if (Admin::user()->can('entity.column.subcolumns.all_up')) {
                    $url      = route('entity.column.subcolumns.all_up');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-success pull-right" style="margin-right: 10px"> <i class="fa fa-arrow-up"></i>全部上线</a>');
                }
                // 过滤按钮
                $tools->append(new \App\Admin\Extensions\Tools\Subcolumn\SubcolumnStatus());
                $tools->append(new \App\Admin\Extensions\Tools\Subcolumn\SubcolumnPublished());
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('entity.column.subcolumns.batch_destroy')) {
                        $batch->disableDelete();
                    }
                    // 批量上线按钮
                    if (Admin::user()->can('entity.column.subcolumns.up')) {
                        $batch->add('上线', new \App\Admin\Extensions\Tools\Subcolumn\ReleaseSubcolumn('up'));
                    }
                    // 批量下线按钮
                    if (Admin::user()->can('entity.column.subcolumns.down')) {
                        $batch->add('下线', new \App\Admin\Extensions\Tools\Subcolumn\ReleaseSubcolumn('down'));
                    }
                    // 批量发布按钮
                    if (Admin::user()->can('entity.column.subcolumns.publish_one')) {
                        $batch->add('上线发布', new \App\Admin\Extensions\Tools\Subcolumn\ReleaseSubcolumn('publish'));
                    }
                    // 批量下线按钮
                    if (Admin::user()->can('entity.column.subcolumns.publish_down_one')) {
                        $batch->add('下线发布', new \App\Admin\Extensions\Tools\Subcolumn\ReleaseSubcolumn('publishDown'));
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '名称')->sortable()->editable();
            $grid->column('title', '标题')->sortable()->editable();
            $grid->column('subtitle', '副标题')->sortable()->editable();
            $grid->column('sp.name', 'SP')->sortable();
            $grid->column('ogroup.name', '渠道')->sortable();
            $grid->column('onclick', 'onclick点击事件')->sortable();
            $grid->column('onfocus', 'onfocus焦点事件')->sortable();
            $grid->column('restful', 'restful路由')->sortable();
            $grid->column('description', '描述')->sortable();
            $grid->column('column.name', '所属栏目')->sortable();
            $uploadConfig = config('custom.base.upload.subcolumn');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $uploadHosts  = config('custom.base.host');
            $host         = $uploadHosts[$driver];
            $grid->column('img', '栏目图片')->image($host);
            // 2017/08/23 tian modify 添加媒资为跳转编辑
            // $grid->vassetis('剧集')->pluck('name')->label();
            $grid->column('short_desc', '简介')->sortable();
            $grid->column('long_desc', '详述')->sortable();
            $grid->column('listorder', '排序')->sortable()->editable();
            $grid->column('online_at', '上线日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            $grid->column('offline_at', '下线日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            $grid->column('online_status', '上线状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-red">下线</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-green">上线</span>';
                        break;
                    default:
                        return '未知';
                }
            })->sortable();
            $grid->column('publish_status', '发布状态')->display(function ($val) {
                switch ($this->online_status) {
                    case 0:
                        switch ($this->publish_down_status) {
                            case 0:
                                return '<span class="badge bg-red">下线未发布</span>';
                                break;
                            case 1:
                                return '<span class="badge bg-green">下线已发布</span>';
                                break;
                            default:
                                return '未知';
                        }
                        break;
                    case 1:
                        switch ($this->publish_status) {
                            case 0:
                                return '<span class="badge bg-red">上线未发布</span>';
                                break;
                            case 1:
                                return '<span class="badge bg-green">上线已发布</span>';
                                break;
                            default:
                                return '未知';
                        }
                        break;
                    default:
                        return '未知';
                }
            })->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();
                // 所属栏目
                $tempColumns = Column::pluck('name', 'id');
                $filter->equal('column_id', '栏目')->select($tempColumns);
                // 状态
                // $aStatus = array(
                //     'online'  => '上线',
                //     'offline' => '下线',
                //     'stop'    => '停用',
                // );
                // $filter->is('status', '状态')->select($aStatus);

                // 编号
                // $filter->like('subcolumn_no', '编号');
                // 名称
                $filter->like('name', '名称');
                // 标题
                $filter->like('title', '标题');
                // 上线时间
                $filter->between('online_at', '上线时间')->datetime();
                // 下线时间
                $filter->between('offline_at', '下线时间')->datetime();
            });
        });
    }

    /**
     * 全部上线功能
     */
    public function allUp()
    {
        if (Admin::user()->cannot('entity.column.subcolumns.all_up')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        $total_num = DB::table('subcolumns as a')
            ->join('subcolumn_vassetis as b', 'a.id', '=', 'b.subcolumn_id')
            ->where(['online_status' => 0, 'publish_down_status' => 1])
            ->pluck('a.id')->unique()->count();
        $notices = [];
        // 已经上线的ids
        $notices[] = [Subcolumn::where(['online_status' => 1])->pluck('id'), 'ID为以下的二级栏目已经上线'];
        // 还未下线发布的ids
        $notices[] = [Subcolumn::where(['publish_down_status' => 0])->pluck('id'), 'ID为以下的二级栏目还未下线发布'];
        // 没有媒资的ids
        $notices[] = [DB::table('subcolumns as a')
                ->whereNotExists(function ($query) {
                    $query->select(DB::raw(1))
                        ->from('subcolumn_vassetis as b')
                        ->whereRaw('a.id = b.subcolumn_id');
                })
                ->whereNull('deleted_at')
                ->pluck('a.id'),
            'ID为以下的二级栏目下面没有媒资',
        ];
        // 拼装提示信息
        $oparation  = '二级栏目上线';
        $totalNum   = Subcolumn::count();
        $successNum = $total_num;
        $failNum    = $totalNum - $successNum;
        $content    = Publication::makeNoticeInfo($oparation, $totalNum, $successNum, $failNum, $notices);
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data   = ['task_type' => '二级栏目上线', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new SubcolumnJob(['dispatch', 'up'], '', $taskid));
        // return response()->json(['content' => $notices]);
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 全部下线功能
     */
    public function allDown()
    {
        if (Admin::user()->cannot('entity.column.subcolumns.all_down')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Publication::getTotalNum(new Subcolumn(), ['online_status' => 1]);
        $result = Publication::getTotalNum(new Subcolumn(), [
            [['online_status' => 1], 'ID为以下二级栏目还没上线'],
        ], '二级栏目下线');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data   = ['task_type' => '二级栏目下线', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new SubcolumnJob(['dispatch', 'down'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 发布功能,由于是全部发布,整个操作放入队列
     */
    public static function publish(Request $request)
    {
        if (Admin::user()->cannot('entity.column.subcolumns.publish')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Publication::getTotalNum(new Subcolumn(), ['online_status' => 1, 'publish_status' => 0]);
        $result = Publication::getTotalNum(new Subcolumn(), [
            [['online_status' => 1], 'ID为以下二级栏目还未上线: '],
            [['publish_status' => 0], 'ID为以下二级栏目已经上线发布: '],
        ], '二级栏目发布');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data = ['task_type' => '二级栏目发布', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        // 任务表插入一条记录
        $taskid = Publication::insertTasks($data);
        dispatch(new SubcolumnJob(['dispatch', 'publish'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 下线发布功能
     */
    public function publishDown(Request $request)
    {
        if (Admin::user()->cannot('entity.column.subcolumns.publish_down')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Publication::getTotalNum(new Subcolumn(), ['online_status' => 0, 'publish_down_status' => 0]);
        $result = Publication::getTotalNum(new Subcolumn(), [
            [['online_status' => 0], 'ID为以下二级栏目还未下线: '],
            [['publish_down_status' => 0], 'ID为以下二级栏目已经下线发布: '],
        ], '二级栏目下线发布');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data = ['task_type' => '二级栏目下线发布', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        // 任务表插入一条记录
        $taskid = Publication::insertTasks($data);
        dispatch(new SubcolumnJob(['dispatch', 'publishDown'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 单个,批量上下线功能,单个,批量在售,停售功能,单个发布功能
     */
    public function batchModerate(Request $request)
    {
        $user_id = Admin::user()->id;
        switch ($request->action) {
            // 上线
            case 'up':
                if (Admin::user()->cannot('entity.column.subcolumns.up')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                $hasVassetiIds = DB::table('subcolumns as a')
                    ->join('subcolumn_vassetis as b', 'a.id', '=', 'b.subcolumn_id')
                    ->where(['online_status' => 0, 'publish_down_status' => 1])
                    ->whereIn('a.id', $request->ids)
                    ->pluck('a.id')->unique();
                $notices = [];
                // 已经上线的ids
                $alreadyOnlineIds = Subcolumn::where(['online_status' => 1])->whereIn('id', $request->ids)->pluck('id');
                if ($alreadyOnlineIds->first()) {
                    $notices[] = [$alreadyOnlineIds, 'ID为以下的二级栏目已经上线'];
                }
                // 还未下线发布的ids
                $notPublishDownIds = Subcolumn::where(['publish_down_status' => 0])->whereIn('id', $request->ids)->pluck('id');
                if ($notPublishDownIds->first()) {
                    $notices[] = [$notPublishDownIds, 'ID为以下的二级栏目还未下线发布'];
                }
                // 没有媒资的ids
                $hasNoVassetiIds = DB::table('subcolumns as a')
                    ->whereNotExists(function ($query) {
                        $query->select(DB::raw(1))
                            ->from('subcolumn_vassetis as b')
                            ->whereRaw('a.id = b.subcolumn_id');
                    })
                    ->whereIn('a.id', $request->ids)
                    ->pluck('a.id');
                if ($hasNoVassetiIds->first()) {
                    $notices[] = [$hasNoVassetiIds, 'ID为以下的二级栏目下面没有媒资'];
                }
                // 拼装提示信息
                $oparation  = '二级栏目上线';
                $totalNum   = count($request->ids);
                $successNum = $hasVassetiIds->count();
                $failNum    = $totalNum - $successNum;
                $content    = Publication::makeNoticeInfo($oparation, $totalNum, $successNum, $failNum, $notices);
                // $ids = Publication::myfilter(new Subcolumn(), $request->ids, ['online_status' => 0, 'publish_down_status' => 1]);
                if (!$hasVassetiIds->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                // 获取有媒资的二级栏目ids
                // $hasVassetiIds = SubcolumnVasseti::whereIn('subcolumn_id', $ids)->pluck('subcolumn_id')->unique();
                $result = Publication::updateMany(new Subcolumn(), $hasVassetiIds, [
                    'online_status'       => 1,
                    'publish_down_status' => 0,
                    'user_id'             => $user_id,
                    'online_at'           => date('Y-m-d H:i:s'),
                ]);
                return response()->json(['status' => 'success', 'content' => $result ? $content : '上线操作失败']);
            // 发布
            case 'publish':
                if (Admin::user()->cannot('entity.column.subcolumns.publish')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // $ids = Publication::myfilter(new Subcolumn(), $request->ids, ['online_status' => 1, 'publish_status' => 0]);
                $result = Publication::myfilter(new Subcolumn(), $request->ids, [
                    [['online_status' => 1], 'ID为以下二级栏目还未上线: '],
                    [['publish_status' => 0], 'ID为以下二级栏目已经上线发布: '],
                ], '二级栏目发布');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                // 如果是批量放入队列中处理
                if (count($ids) > 1) {
                    $data   = ['task_type' => '二级栏目发布', 'user_id' => $user_id, 'total_num' => count($ids)];
                    $taskid = Publication::insertTasks($data);
                    dispatch(new SubcolumnJob(['publish'], $ids, $taskid));
                    $url = route('entity.column.subcolumns.progress');
                    return response()->json(['status' => 'queue', 'content' => $content, 'taskid' => $taskid, 'url' => $url]);
                }
                // 如果是单条数据发布
                $subcolumns      = Subcolumn::whereIn('id', $ids)->with('column', 'vassetis')->get();
                $subcolumn_datas = SubcolumnJob::makeSubcolumns($subcolumns);
                $resutl1         = Publication::insertApi('subcolumns', $subcolumn_datas);
                $result2         = Publication::updateMany(new Subcolumn(), $ids, [
                    'publish_status' => 1,
                    'user_id'        => $user_id,
                ]);
                $content = ($resutl1 && $result2) ? $content : '上线发布失败!';
                return response()->json(['status' => 'success', 'content' => $content]);
            // 下线
            case 'down':
                if (Admin::user()->cannot('entity.column.subcolumns.down')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // $ids = Publication::myfilter(new Subcolumn(), $request->ids, ['online_status' => 1]);
                $result = Publication::myfilter(new Subcolumn(), $request->ids, [
                    [['online_status' => 1], 'ID为以下二级栏目还没上线'],
                ], '二级栏目下线');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                $result = Publication::updateMany(new Subcolumn(), $ids, [
                    'online_status'  => 0,
                    'publish_status' => 0,
                    'user_id'        => $user_id,
                    'offline_at'     => date('Y-m-d H:i:s'),
                ]);
                return response()->json(['status' => 'success', 'content' => $result ? $content : '下线操作失败']);
            // 下线发布
            case 'publishDown':
                if (Admin::user()->cannot('entity.column.subcolumns.publish_one')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // $ids = Publication::myfilter(new Subcolumn(), $request->ids, ['online_status' => 0, 'publish_down_status' => 0]);
                $result = Publication::myfilter(new Subcolumn(), $request->ids, [
                    [['online_status' => 0], 'ID为以下二级栏目还未下线: '],
                    [['publish_down_status' => 0], 'ID为以下二级栏目已经下线发布: '],
                ], '二级栏目下线发布');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                /*
                 * 删除接口库中对应的数据
                 * 这里有两种可能的情况
                 * 1.资源还没有上线发布就被下线, 接口库没有还没有这个资源
                 * 2.资源已经上线发布过, 接口库中有这个资源
                 * 所以在删除接口库中的数据时, 需要先判断接口库中是否有对应数据, 有则返回删除操作的结果, 没有则直接返回true
                 */
                $subcolumnsCount = DB::connection('interface')->table('subcolumns')->whereIn('subcolumnid', $ids)->count();
                if ($subcolumnsCount) {
                    // 删除接口库中对应的数据
                    $result1 = Publication::deleteApi('subcolumns', 'subcolumnid', $ids);
                } else {
                    $result1 = true;
                }
                // 更新状态
                $result2 = Publication::updateMany(new Subcolumn(), $ids, [
                    'publish_down_status' => 1,
                    'user_id'             => $user_id,
                ]);
                return response()->json(['status' => 'success', 'content' => $result1 && $result2 ? $content : '下线发布失败!']);
        }
    }

    /**
     * 查询进度
     */
    public function queryProgress(Request $request)
    {
        $taskid = (int) $request->input('taskid');
        return Publication::progress($taskid);
    }
}
